<script type="text/javascript" language="javascript">
    var maxprogress = 200;   // total to reach
    var actualprogress = 0;  // current value
    var itv = 0;  // id to setinterval
    var autoMove = false;
    var markerArray = new Array();//
    var ipage = 1;
    var current = 1;
    var display = 8;

    var ws;
    var socket = ""; // socket is returned from server

    var avatar;
    var info_frame;
    var back_btt;
    var next_btt;
    var background_listroom;
    var exp;
    var level;
    var lvImage;

    var canvas,ctx;
    var canvas1,ctx1;
    var canvas2,ctx2;
    var backgroundImage, backgroundImage1;
    var dragon = new Array();
    var house;
    var dragonW = 75; // dragon width
    var dragonH = 70; // dragon height
    var iSprPos = 0; // initial sprite frame
    var iSprPosArray = new Array();
    var iSprDir = 0; // initial dragon direction
    var bMouseDown = false; // mouse down state
    var iLastMouseX = 0;
    var iLastMouseY = 0;
    var iScene = 2;
    var radio = [];
    var answerBtn;
    var room;// room.png
    var title; //title.png
    var player;
    var x_btt = new Array(); // button x
    var btt;
    var start_btt;
    var start_btt2;
    var ready_btt;
    var unready_btt;
    var btt_invite;
    var btt_back_to_list_room;
    var btt_play_with_pc;
    var userInRoom = null;
    var isReady = false;
    var listroom;
    var question;
    var Start = false; // can click Start
    var StartGame = false;
    var right = new Array();

    var question_frame;
    var frame_panel;
    var frame_info;
    var frame_message_box;
    var check_img;
    
    var r_listroom = new Array(); // list room to right
    var l_listroom = new Array(); // list room to left

    var arrQuestion = new Array();// array question show in scene 2
    var play_with_pc = false;
	
	var list_free_player;

    var avatar_url;
    var setting;

    var option = 1;

    var iCorrectAnswer=0;
    var correctAns_frame;

    var id_room; //room was playing
    var finish_line;
    var invite_form;

    function Form(x, y, w, h, accept_btt, close_btt, image, flag){
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.accept_btt = accept_btt;
        this.close_btt = close_btt;
        this.image = image;
        this.flag = flag;// 1: show
    }

    //zone positions
    var position = {
        dragon1: {
            x: 50,//50
            y: 150
        },
        dragon2: {
            x: 50,
            y: 210
        },
        dragon3: {
            x: 50,
            y: 270
        },
        dragon4: {
            x: 50,
            y: 330
        }
    };   

            function Room(id, x1, x2, y1, y2){
        this.id = id;
        this.x1 = x1;
        this.x2 = x2;
        this.y1 = y1;
        this.y2 = y2;
    }
	
            function Character(x, y, w, h, image) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.image = image;
        this.bDrag = false;
    }

            function House(x,y,w,h,state, image) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.state = state;
        this.imageShift = 0;
        this.image = image;
    }

            function Radio (x,y,w,h,image1, image2) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.check  = false;
        this.imageCheck = image1;
        this.imageUncheck = image2;
    }

            function GameButton(x,y,w,h,image){
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;        
        this.image = image;
        this.press = 0;
    }

            function prog()    {
        if(actualprogress >= maxprogress)
        {
            var cAnswer = parseInt(question['correct']) - 1;
            ctx2.drawImage(check_img, 0, 0, check_img.width, check_img.height, radio[cAnswer].x-17,radio[cAnswer].y+3, 15, 15);
            //clearInterval(itv);
            // draw correctAnswer
            return;
        }
        var indicator = document.getElementById("indicator");
        actualprogress += 2;
        indicator.style.width=actualprogress + "px";
        if(actualprogress >= 150){
            indicator.style.background ='url(<?php echo elgg_get_site_url(); ?>mod/game/graphics/red.png)';
        }
        if(actualprogress == maxprogress) {
            //clearInterval(itv);

            var rightAns = CheckAnswer()?CheckAnswer():false; // true if having right answer
            if( rightAns){
                send("HAVE_RIGHT_ANSWER",1);
                iCorrectAnswer++;
            }
            else
                send("HAVE_RIGHT_ANSWER",0);
        }
    }

            function DrawNB(){
        ctx1.drawImage(title, 1100/2-title.width/2, 23);
        ctx1.drawImage(back_btt.image, 0, 0, 326, 71, back_btt.x, back_btt.y, back_btt.w, back_btt.h);
        //ctx1.drawImage(back_btt.image,back_btt.x, back_btt.y);
        ctx1.drawImage(next_btt.image, 0, 0, 330, 71, next_btt.x, next_btt.y, next_btt.w, next_btt.h);
        //ctx1.drawImage(next_btt.image, next_btt.x, next_btt.y);
        
        ctx1.drawImage(start_btt2.image, 0, 0, start_btt2.w, start_btt2.h, start_btt2.x, start_btt2.y, start_btt2.w/3, start_btt2.h/3);
    }

            function Draw_Ready(ready){
        ctx.drawImage(title, 1100/2-title.width/2, 23);
        ctx.drawImage(btt_back_to_list_room.image, btt_back_to_list_room.x, btt_back_to_list_room.y);
        if( userInRoom['player'].length == 1)
            ctx.drawImage(btt_play_with_pc.image, btt_play_with_pc.x, btt_play_with_pc.y);
        
        var bg_gradient = ctx.createLinearGradient(0, 200, 0, 400);
        bg_gradient.addColorStop(0.0, 'rgba(160, 160, 160, 0.8)');
        bg_gradient.addColorStop(1.0, 'rgba(250, 250, 250, 0.8)');

        if(!play_with_pc){
            //ctx.drawImage(btt_invite, 0,0,128,128,850,400,30,30);
            ctx.drawImage(btt_invite.image, btt_invite.x, btt_invite.y);
        }
        if(userInRoom != null && !play_with_pc){
            if(userInRoom['host'] == <?php echo elgg_get_logged_in_user_guid() ?>){
                ctx.drawImage(setting.image, setting.x, setting.y);

                var canStart = 0;
                for( var i = 0 ; i < userInRoom['ready'].length ; ++i){
                    if( userInRoom['ready'][i] == 1){
                        canStart++;
                    }
                }

                if( canStart != 0 && canStart == userInRoom['player'].length - 1){
                    Start = true;
                    ctx.drawImage(start_btt.image, start_btt.x, start_btt.y);
                }
            }
            else{
                if( ready == false)
                    ctx.drawImage(ready_btt.image, ready_btt.x, ready_btt.y);
                    //ctx.fillText('Ready' ,900 , 515 );
                else
                    ctx.drawImage(unready_btt.image, unready_btt.x, unready_btt.y);
                    //ctx.fillText('Unready' ,900 , 515 );
            }
        }
    }

            function DrawPlayerInfo() {
        ctx.drawImage(frame_info, 0, 0, frame_info.width, frame_info.height, 48, 23,frame_info.width, frame_info.height-20);
        ctx.font = '18px DS-Digital';
        ctx.textAlign = 'left';
        ctx.textBaseline = 'top';
        ctx.shadowColor = '#000';

        ctx.shadowBlur = 2;
        ctx.fillStyle = '#fff';

        ctx.fillText('Name: <?php echo elgg_get_logged_in_user_entity()->name; ?> ',60 , 30 );
        ctx.fillText('Exp:  '+ exp,60 , 60 );
        ctx.fillText('Level:  ',60 , 90 );
        ctx.drawImage(lvImage, 0, 0, lvImage.width, lvImage.height, 120, 85, 30, 30);
    }

            function DrawInfo(){ // in scene 2
       
        ctx1.drawImage(info_frame, 0, 0, info_frame.width, info_frame.height, 800, 80, 250, 280);
        ctx1.drawImage(avatar, 780 + (1100 - 810 - avatar.width)/2, 135);

        ctx1.font = '18px DS-Digital';
        ctx1.shadowColor = "rgb(30, 30, 30)";
        
        ctx1.textAlign = 'left';
        ctx1.textBaseline = 'top';
        ctx1.shadowColor = '#000';

        ctx1.shadowBlur = 2;
        ctx1.fillStyle = '#111';

        ctx1.fillText(level, 850, 140 + avatar.height + 25 );
        ctx1.drawImage(lvImage, 0, 0, lvImage.width, lvImage.height, 950, 140 + avatar.height + 12, 40, 40);

        ctx1.fillText('Exp', 850, 140 + avatar.height + 70 );
        ctx1.fillText(exp, 950, 140 + avatar.height + 70 );

        ctx1.font = 'bold 18px DS-Digital';
        ctx1.textAlign = 'center';
        //        ctx1.shadowOffsetX = 2;
        //        ctx1.shadowOffsetY = 3;
        ctx1.fillText('<?php echo elgg_get_logged_in_user_entity()->name; ?> ', 780 + (1100 - 810)/2, 100 );    
            }

            function getLevel(level){
                // var img = new Image();
                var lvText = ";"
                switch(level){
                    case 1:
                        lvText = "Primary";
                        break;
                    case 2:
                        lvText = "Highschool";
                        break;
                    case 3:
                        lvText = "College";
                        break;
                    case 4:
                        lvText = "Univesity";
                        break;
                    case 5:
                        lvText = "Graduated";
                        break;
                    default:
                        lvText = "Preschool";
                        break;
                }
                return lvText;
                //return img.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/level/' + lvText + '.png';
            }

            function DrawQuestion(content) {
                if(content != null){
                    var type = parseInt(content['type']);
                    switch(type){
                        case 1:
                            Draw1(content);
                            break;
                        case 2:
                            Draw2(content);                            
                            break;
                        default:
                            break;
                    }
                }
            }

            function Draw1(content){ // draw question in type 1
                    ctx2.font = '18px DS-Digital';
                    ctx2.textAlign = 'left';
                    ctx2.textBaseline = 'top';
                    ctx2.shadowColor = '#000';

                    ctx2.shadowBlur = 2;
                    ctx2.fillStyle = '#000';

                    ctx2.drawImage(question_frame, 0, 0, question_frame.width, question_frame.height, 0,0, canvas2.width, canvas2.height);
                    if(content['title'].length > 25)
                        ctx2.fillText(content['title'] , canvas2.width/5 , 30);
                    else
                        ctx2.fillText(content['title'] , canvas2.width/3 , 30);
                    for(var i = 0; i < radio.length; i++) {
                        if(radio[i].check == false)
                            ctx2.drawImage(radio[i].imageUncheck, radio[i].x, radio[i].y);
                        else
                            ctx2.drawImage(radio[i].imageCheck, radio[i].x, radio[i].y);                        
                        ctx2.fillText (content['answer'+(i+1)], radio[i].x + 30, radio[i].y);
                    }                    

                    var progress = document.getElementById("progressbar");
                    progress.style.border = "1px solid black";
                    prog();
            }

            function Draw2(content){
                if(content['url'] != null){
                    //draw Image
                    //
                    var audio =   '<audio  controls autoplay="autoplay" style="z-index: 6; position:absolute; width:300px; left: 400px; top: 50px;">'+
                                  '<source src="'+'<?php echo elgg_get_site_url(); ?>mod/game/sound/'+ content['url']+'.mp3'+ '" type="audio/mp3" />'+
                                  //'<source src="song.mp3" type="audio/mp3" />'+
                                  'Your browser does not support the audio tag.'+
                                  'audio>';
                    $("#container").append(audio);
                    question['url'] = null;
                }
                var array = new Array("A", "B", "C");
                for(var i = 0; i < radio.length; i++) {
                        if(radio[i].check == false)
                            ctx2.drawImage(radio[i].imageUncheck, radio[i].x, radio[i].y);
                        else
                            ctx2.drawImage(radio[i].imageCheck, radio[i].x, radio[i].y);
                        ctx2.font = '18px DS-Digital';
                        ctx2.fillStyle = 'white';
                        ctx2.textAlign = 'left';
                        ctx2.fillText (array[i], radio[i].x + 30, radio[i].y + 15);
                    }
            }

            function CheckAnswer(){      // dang code cung, chua linh hoat question[i]
                for( var i = 0; i < radio.length; i++){
                    if (radio[i].check == true){
                        if((i+1) == parseInt(question['correct'])){
                            return true;
                        }
                    }
                }

                return false;
            }

            function drawScene() {
                ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx2.clearRect(0, 0,canvas2.width, canvas2.height);
                // $("#sltLevel").hide();
                //        if(iScene == 1){
                //            ctx.drawImage(backgroundMenu, 0, 0, backgroundMenu.width,backgroundMenu.height, 0, 0, 1090, 600);//, 0, 0, 1000, 600);//, 0 ,0, 1044, 644);//, 0, 0 , 1200, 600);//, 1076, 716, 0, 0, 1000, 600);
                //        }
                //else
                
                if( iScene == 2){
                    //ctx1.drawImage(backgroundImage, 0, 0, 1100, 600);//, 0 , 0, 1044, 644);
                    ctx1.drawImage(backgroundImage, 0, 0, backgroundImage.width,backgroundImage.height, 0, 0, 1090, 600);
                    ctx1.drawImage(background_listroom, 0, 0, background_listroom.width, background_listroom.height, 45, 20, 998, 555);//, 50, 50, 212, 62);
                    ctx1.drawImage(frame_message_box, 0, 0, frame_message_box.width, frame_message_box.height, 45, 428, 380, 147);
                    DrawNB();
                    DrawInfo();
                    
                }
                else if(iScene == 3){
                    //ctx.drawImage(backgroundImage, 0, 0);
                    ctx.drawImage(backgroundImage, 0, 0, backgroundImage.width,backgroundImage.height, 0, 0, 1090, 600);
                    ctx.drawImage(background_listroom, 0, 0, background_listroom.width, background_listroom.height, 45, 20, 998, 555);//, 50, 50, 212, 62);
                    ctx.drawImage(frame_message_box, 0, 0, frame_message_box.width, frame_message_box.height, 45, 428, 380, 147);									
                }
                


                if(iScene == 3 && autoMove && right != null && StartGame == true) {

//                iSprPos++;
//                if (iSprPos >= 6) {
//                    iSprPos = 0;
//                }
//
                    // for(var marker = 0; marker < markerArray.length; marker++){
                    for( var i = 0 ; i < right.length ; ++i){
                        iSprPosArray[right[i]]++;
                        if (iSprPosArray[right[i]] >= 6) {
                            iSprPosArray[right[i]] = 0;
                        }

                        if(markerArray[right[i]][0] > dragon[right[i]].x){
                            dragon[right[i]].x += 2;                            
                        }
                    }
                    if( dragon[right[right.length-1]].x == markerArray[right[right.length-1]][0]){//last dragon has already draw
					
			for( var j = 0 ; j < right.length ; ++j){
                            if(dragon[right[j]].x == markerArray[right[j]][markerArray[right[j]].length - 1]){
                                send("FINISH_GAME","");
                                right = null;
                                return;
                            }
                            
                            if(markerArray[right[j]][0] == dragon[right[j]].x) {
                                iSprPosArray[right[j]] = 0;
                                markerArray[right[j]].splice(0, 1);
                                
                            }
                        }
                        //for( var i = 0 ; i < right.length ; ++i)
                            
										
                        
                        if(userInRoom['host'] == <?php echo elgg_get_logged_in_user_guid() ?>){
                            var t= setTimeout(function(){send("DRAW_QUES", option);}, 2000);
                        }
                        var t= setTimeout(function(){
                            
                            actualprogress = 0;
                            for( var i = 0; i < radio.length; i++){
                                if (radio[i].check == true){
                                    radio[i].check = false;
                                    break;
                                }
                            }
                        }, 2000);
				right = null;
						
                    }
                }

                if( iScene == 2){
                    var progress = document.getElementById("progressbar");
                    progress.style.border = "0px solid black";
                    actualprogress = 0;
                    indicator.style.width=actualprogress + "px";
                    showroom( listroom);
                }
                if(iScene ==3) {
                
                    DrawPlayerInfo();
                    if( StartGame == false){
                        //$("#sltLevel").show();
                        Draw_Ready(isReady);
                    }
                
                    for( var i = 0 ; i < userInRoom['player'].length ; ++i){
                        ctx.drawImage(dragon[userInRoom['player'][i]].image, iSprPosArray[userInRoom['player'][i]]*dragon[userInRoom['player'][i]].w, iSprDir*dragon[userInRoom['player'][i]].h, dragon[userInRoom['player'][i]].w, dragon[userInRoom['player'][i]].h, dragon[userInRoom['player'][i]].x, dragon[userInRoom['player'][i]].y, dragon[userInRoom['player'][i]].w*1/3, dragon[userInRoom['player'][i]].h*1/3);
                        ctx.font = '10px DS-Digital';
                        ctx.textAlign ='left';
                        ctx.fillStyle = '#fff';
                        ctx.fillText(userInRoom['name'][i], dragon[userInRoom['player'][i]].x, dragon[userInRoom['player'][i]].y+dragon[userInRoom['player'][i]].h*1/3);
                        if(userInRoom['host'] == <?php echo elgg_get_logged_in_user_guid() ?> && StartGame == false){
                            if( userInRoom['player'][i] != userInRoom['host'] && userInRoom['player'][i] != 0){
                                ctx.drawImage( x_btt[userInRoom['player'][i]].image, x_btt[userInRoom['player'][i]].x, x_btt[userInRoom['player'][i]].y);
                            }
                        }
                        if(userInRoom['ready'][i] && StartGame == false){
                            ctx.drawImage(check_img, 0, 0, check_img.width, check_img.height, x_btt[userInRoom['player'][i]].x + dragon[userInRoom['player'][i]].w*1/3, x_btt[userInRoom['player'][i]].y, 10, 10);
                        }
                    }
                    if( StartGame == true){                        
                        DrawQuestion(question);
                        ctx.drawImage(correctAns_frame, 0, 0, 375, 240, canvas.width-120-160+100, canvas.height-77-30, 120, 77);
                        ctx.font = '20px DS-Digital';
                        ctx.textAlign ='left';
                        ctx.fillStyle = 'red';
                        
                        ctx.fillText(iCorrectAnswer, canvas.width-120-95+100, canvas.height-77-5);
                        ctx.fillText(arrQuestion.length, canvas.width-120-75+100, canvas.height-77+20);
                        
                        ctx.drawImage(finish_line,0, 0, finish_line.width, finish_line.height, 1018, 130, 24, 330);
                    }                    
                }
                if( invite_form.flag){
                    if( iScene ==2){
                        ctx1.drawImage( invite_form.image, invite_form.x, invite_form.y);
                        ctx1.drawImage(invite_form.close_btt.image, invite_form.close_btt.x, invite_form.close_btt.y);
                        ctx1.drawImage(invite_form.accept_btt.image, invite_form.accept_btt.x, invite_form.accept_btt.y);
                    }
                        else if(iScene == 3){

                        }
                }
            }

            function initGame() {
                var inner = $(".elgg-page-body .elgg-inner");
                inner[0].style.width = "1100px";

                canvas = document.getElementById('scene');
                ctx = canvas.getContext('2d');
                canvas1 = document.getElementById('scene1');
                ctx1 = canvas1.getContext('2d');
                canvas2 = document.getElementById('scene2');
                ctx2 = canvas2.getContext('2d');

                var width = canvas.width;
                var height = canvas.height;

                var url = '<?php
                    $user = get_user(elgg_get_logged_in_user_guid());
                    $url = $user->getIconURL('medium');
                    echo $url;
                    ?>';
                avatar = new Image();
                avatar.src = url;
        
                exp =<?php
                    $user = get_user(elgg_get_logged_in_user_guid());
                    $exp = $user->exp;
                    echo $exp;
                    ?>;

                var $level =<?php
                    $user = get_user(elgg_get_logged_in_user_guid());
                    $level = $user->level;
                    echo $level;
                    ?>;

                level = getLevel($level);
                lvImage = new Image();
                lvImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/level/' + level + '.png';

                check_img = new Image();
                check_img.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/check.png';

                back_img = new Image();
                back_img.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/back_btt.png';
                back_btt = new GameButton(585, 425, 100, 25, back_img);

                next_img = new Image();
                next_img.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/next_btt.png';
                next_btt = new GameButton(695, 425, 100, 25, next_img);

                settingImg = new Image();
                settingImg.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/setting.png';
                setting = new GameButton(canvas.width-150, canvas.height-100, 60, 60, settingImg);

                background_listroom = new Image;
                background_listroom.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/background_listroom.png';

                backgroundMenu = new Image();
                backgroundMenu.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/background_menu.png';

                backgroundImage = new Image();
                backgroundImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/game_bg.gif';

                frame_panel = new Image();
                frame_panel.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/listroom_frame.png';

                info_frame = new Image();
                info_frame.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/info_frame.png';

                frame_info = new Image();
                frame_info.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/FramePanel.png';

                frame_message_box = new Image();
                frame_message_box.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/MessageBox.jpg';

                question_frame = new Image();
                question_frame.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/question_frame.png';
        
                room = new Image();
                room.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/room.png';

                title = new Image();
                title.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/go xitrum.png';

                start_img = new Image();
                start_img.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/Start_btt.png';
                start_btt = new GameButton(canvas.width/2-150/2, canvas.height/2-150/2, 150, 150, start_img);

                start_img = new Image();
                start_img.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/Start_btt2.png';
                start_btt2 = new GameButton(810, 430, 658, 260, start_img);

                ready_img = new Image();
                ready_img.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/Ready_btt.png';
                ready_btt = new GameButton(canvas.width/2-150/2, canvas.height/2-150/2, 150, 150, ready_img);

                unready_img = new Image();
                unready_img.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/Unready_btt.png';
                unready_btt = new GameButton(canvas.width/2-150/2, canvas.height/2-150/2, 150, 150, unready_img);

                btt_invite_img = new Image();
                btt_invite_img.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/invite_friends_icon.png';
                btt_invite = new GameButton(150, 160, 30, 30, btt_invite_img); //850, 400, 30, 30

                btt_back_to_list_room_img = new Image();
                btt_back_to_list_room_img.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/back_list_room_btt.png';
                btt_back_to_list_room = new GameButton(585, 510, 106, 40, btt_back_to_list_room_img);

                btt_play_with_pc_img = new Image();
                btt_play_with_pc_img.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/vs_pc_btt.png';
                btt_play_with_pc = new GameButton(700, 510, 106, 40, btt_play_with_pc_img);

                player = new Image();
                player.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/user_red.png';

                finish_line = new Image();
                finish_line.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/finish_line.png';

                correctAns_frame = new Image();
                correctAns_frame.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/iCorrectAnswer.png';

                for(var i =0; i<radio.length;i++) {
                    var radio_uncheckImage  = new Image();
                    var radio_checkImage  = new Image();
                    radio_uncheckImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/radio_uncheck.png';
                    radio_checkImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/radio_checked.png';
                    if( i%2 == 0)
                        radio[i] = new Radio(canvas2.width/2 - 150, 45 + i*19, 19,19, radio_checkImage, radio_uncheckImage );
                    else
                        radio[i] = new Radio(canvas2.width/2 + 150, 45 + (i-1)*19, 19,19, radio_checkImage, radio_uncheckImage );
                }
            var accept_image = new Image();
            accept_image.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/form/ToggleButton_pressedImage.png';
            var accept_btt = new GameButton(canvas.width/2- 25, canvas.height/2 + 45, 49, 19, accept_image);

            var close_image = new Image();
            close_image.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/form/Frame_closeIcon_rolloverImage.png';
            var close_btt = new GameButton(canvas.width/2+140, canvas.height/2 - 80, 69, 26, close_image);
            
            var form_image = new Image();
            form_image.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/form/Frame_activeBG.png';
            invite_form = new Form(canvas.width/2-378/2, canvas.height/2-169/2, 378, 169, accept_btt, close_btt, form_image, 0);

                $('#scene').mousedown(function(e) { // binding mousedown event (for dragging)
                    var mouseX = e.layerX || 0;
                    var mouseY = e.layerY || 0;
                    if(e.originalEvent.layerX) { // changes for jquery 1.7
                        mouseX = e.originalEvent.layerX;
                        mouseY = e.originalEvent.layerY;
                    }

                    bMouseDown = true;

                    //Press Ready
                    if(iScene == 3 && mouseX > start_btt.x && mouseX < start_btt.x+start_btt.w && mouseY > start_btt.y && mouseY < start_btt.y+start_btt.h) {
                        if(userInRoom['host'] != <?php echo elgg_get_logged_in_user_guid() ?>){
                            if( !isReady){
                                isReady = true;
                                send("READY","");
                            }
                            else{
                                isReady = false;
                                send("UNREADY","");
                            }
                        }
                        ////////////////
                        //   START   ///
                        ////////////////
                        else{
                            if( Start == true && StartGame == false){
                                send("START_GAME", '"'+option+'"');  //level of questions
                            }
                        }
                    }

                    //PLAY WITH PC by Next Button
                    if(iScene == 3 && userInRoom['player'].length == 1 && mouseX > btt_play_with_pc.x && mouseX < (btt_play_with_pc.x+btt_play_with_pc.w) && mouseY > btt_play_with_pc.y && mouseY < (btt_play_with_pc.y+btt_play_with_pc.h)) {
                        send("PLAY_WITH_PC","");
                        play_with_pc = true;
                    }

                    ////Invite friend
                    if(iScene == 3 && mouseX > btt_invite.x && mouseX < (btt_invite.x+btt_invite.w) && mouseY > btt_invite.y && mouseY < (btt_invite.y+btt_invite.h)) {
                        send("LIST_FREE_PLAYER", "");
                    }
                    ///////////////Press Back to back to list room
                    if(iScene == 3 && mouseX > btt_back_to_list_room.x && mouseX < (btt_back_to_list_room.x+btt_back_to_list_room.w) && mouseY > btt_back_to_list_room.y && mouseY < (btt_back_to_list_room.y+btt_back_to_list_room.h)) {
                        send("QUIT_ROOM", "");
                    }
                    //////////////Setting
                    if(iScene == 3 && !play_with_pc && mouseX > setting.x && mouseX < (setting.x+setting.w)&& mouseY > setting.y && mouseY < (setting.y+setting.h)) {
                        Option();
                    }
                    //////////////KICK_ROOM
                    if(StartGame == false){
                        for( var i = 0 ; i < userInRoom['player'].length ; ++i){
                            if(x_btt[userInRoom['player'][i]].x < mouseX && x_btt[userInRoom['player'][i]].x + 21 > mouseX && x_btt[userInRoom['player'][i]].y < mouseY && x_btt[userInRoom['player'][i]].y + 28 > mouseY)
                                send("KICK_ROOM", userInRoom['player'][i]);
                        }
                    }
                });

                $('#scene1').mousedown(function(e) {
                    var mouseX = e.layerX || 0;
                    var mouseY = e.layerY || 0;
                    if(e.originalEvent.layerX) { // changes for jquery 1.7
                        mouseX = e.originalEvent.layerX;
                        mouseY = e.originalEvent.layerY;
                    }
                    //invite form
                    if(mouseX > invite_form.accept_btt.x && mouseX < (invite_form.accept_btt.x+invite_form.accept_btt.w) && mouseY > invite_form.accept_btt.y && mouseY < (invite_form.accept_btt.y+invite_form.accept_btt.h)) {
                        send("JOIN_ROOM",'"'+id_room+'"');
                    }
                    if(mouseX > invite_form.close_btt.x && mouseX < (invite_form.close_btt.x+invite_form.close_btt.w) && mouseY > invite_form.close_btt.y && mouseY < (invite_form.close_btt.y+invite_form.close_btt.h)) {
                        invite_form.flag = 0;
                    }
                    //  Press Back IN List Room
                    if(mouseX > back_btt.x && mouseX < (back_btt.x+back_btt.w) && mouseY > back_btt.y && mouseY < (back_btt.y+back_btt.h)) {
                        if( current > 1)
                            current--;
                        else
                            current = ipage;
                        send("LIST_ROOM", current);
                    }
                    // Press Next IN List Room
                    else if(mouseX > next_btt.x && mouseX < (next_btt.x+next_btt.w) && mouseY > next_btt.y && mouseY < (next_btt.y+next_btt.h)) {
                        if( current < ipage)
                            current++;
                        else
                            current = 1;
                        send("LIST_ROOM", current);
                    }

                    //Press Start to New Room
                    else if(mouseX > start_btt2.x && mouseX < (start_btt2.x+start_btt2.w/3) && mouseY > start_btt2.y && mouseY < (start_btt2.y+start_btt2.h/3)) {
                        // send request to server to create new room
                        send("NEW_ROOM", "");
                    }
                    // Press to join room
                    else if( mouseX <= (80 + room.width) && mouseX >= 80){  // use l_listroom
                        var Y = mouseY;//- 100;
                        for( var i = 0 ; i < l_listroom.length ; ++ i){
                            if( Y > l_listroom[i].y1 && Y < l_listroom[i].y2){
                                id_room = l_listroom[i].id;
                                send("JOIN_ROOM", '"'+l_listroom[i].id+'"');
                                break;
                            }
                        }
                    }

                    else if( mouseX <= (440 + room.width) && mouseX >= 440){  // use l_listroom
                        var Y = mouseY;// - 100;
                        for( var i = 0 ; i < r_listroom.length ; ++ i){
                            if( Y > r_listroom[i].y1 && Y < r_listroom[i].y2){
                                //alert( i * 2 + 1);
                                id_room = r_listroom[i].id;
                                send("JOIN_ROOM", '"'+r_listroom[i].id+'"');
                                break;
                            }
                        }
                    }
                });

                $('#scene2').mousedown(function(e) {
                    var mouseX = e.layerX || 0;
                    var mouseY = e.layerY || 0;
                    if(e.originalEvent.layerX) { // changes for jquery 1.7
                        mouseX = e.originalEvent.layerX;
                        mouseY = e.originalEvent.layerY;
                    }

                    

                    for( var i = 0 ; i<radio.length;++i){
                        if(mouseX > radio[i].x && mouseX < radio[i].x+radio[i].w && mouseY > radio[i].y && mouseY < radio[i].y+radio[i].h) {
                            for( var j = 0 ; j<radio.length;++j){
                                if(j!=i) {
                                    radio[j].check = false;
                                }
                            }
                            radio[i].check = true;
                            break;
                        }
                    }
                });

                $('#scene1').mousemove(function(e) { // binding mousemove event
                    var mouseX = e.layerX || 0;
                    var mouseY = e.layerY || 0;
                    if(e.originalEvent.layerX) { // changes for jquery 1.7
                        mouseX = e.originalEvent.layerX;
                        mouseY = e.originalEvent.layerY;
                    }
                    //alert(mouseX+", "+mouseY);
                    
                    if(mouseX > start_btt2.x && mouseX < (start_btt2.x+start_btt2.w/3) && mouseY > start_btt2.y && mouseY < (start_btt2.y+start_btt2.h/3)) {
                        //start_btt2.press = 1;
                        //start_btt2.image.src = '<?php //echo elgg_get_site_url(); ?>mod/game/graphics/Start_btt2_copy.png';
                    }
                    else{
                        //start_btt2.press = 0;
                        //start_btt2.image.src = '<?php //echo elgg_get_site_url(); ?>mod/game/graphics/Start_btt2.png';
                    }

//                    if(mouseX > back_btt.x && mouseX < (back_btt.x+back_btt.w) && mouseY > back_btt.y && mouseY < (back_btt.y+back_btt.h)) {
//                        back_btt.image.src = '<?php //echo elgg_get_site_url(); ?>mod/game/graphics/back_btt_copy.png';
//                    }
//                    else{
//                        back_btt.image.src = '<?php //echo elgg_get_site_url(); ?>mod/game/graphics/back_btt.png';
//                    }
//
//                    if(mouseX > next_btt.x && mouseX < (next_btt.x+next_btt.w) && mouseY > next_btt.y && mouseY < (next_btt.y+next_btt.h)) {
//                        next_btt.image.src = '<?php //echo elgg_get_site_url(); ?>mod/game/graphics/next_btt_copy.png';
//                    }
//                    else{
//                        next_btt.image.src = '<?php //echo elgg_get_site_url(); ?>mod/game/graphics/next_btt.png';
//                    }
                    
                });               

                $("#LoadImage").remove();
                itv = setInterval(drawScene, 30);
            }

            function showroom(listroom){
                //ctx1.drawImage(frame_panel, 0, 0, frame_panel.width, frame_panel.height, 60, 80, 750, 380);
                ctx1.drawImage(frame_panel, 0, 0, frame_panel.width, frame_panel.height, 60, 70, 750, 348);
                r_listroom = new Array(); // list room to right
                l_listroom = new Array();
                //var slg = listroom['slg'];
                var thanhvien = listroom['thanhvien'];
                var id = listroom['id'];
		
                var bg_gradient = ctx1.createLinearGradient(0, 200, 0, 400);
                bg_gradient.addColorStop(0.0, 'rgba(160, 160, 160, 0.8)');
                bg_gradient.addColorStop(1.0, 'rgba(250, 250, 250, 0.8)');
                for( var i = 0 ; i < thanhvien.length; ++i){
                    //if( i < slg){
                    if( i%2 == 0){
                        l_listroom.push( new Room(id[i], 80, room.width + 80, 95 + (i/2) * (room.height + 10), 95 + (i/2) * (room.height + 10) + room.height)); // width: 351 height: 67
                        ctx1.drawImage(room, 80, 95 + (i/2) * (room.height + 10));

                        ctx1.font = '20px DS-Digital';
                        ctx1.textAlign = 'left';
                        ctx1.textBaseline = 'top';
                        ctx1.shadowColor = '#000';
                        ctx1.shadowBlur = 2;
                        ctx1.fillStyle = '#000';
                        ctx1.fillText("Room  " + id[i], 90 , 105 + (i/2) * (room.height + 10) );
                        //ctx1.fillText(thanhvien[i] + "/4" ,40 + 351/2 , 140 + (i/2) * (67 + 20) );
                        for( var j = 0 ; j < thanhvien[i] ; ++j)
                            ctx1.drawImage(player, room.width/2 + j*player.width + 30,140 + (i/2) * (room.height + 10));
                    }
                    else{
                        r_listroom.push( new Room(id[i], 440, room.width + 440, 95 + ((i-1)/2) * (room.height + 10), 95 + ((i-1)/2) * (room.height + 10) + room.height)); // width: 351 height: 67
                        ctx1.drawImage(room, 440, 95 + ((i-1)/2) * (room.height + 10));

                        ctx1.font = '20px DS-Digital';
                        ctx1.textAlign = 'left';
                        ctx1.textBaseline = 'top';
                        ctx1.shadowColor = '#000';
                        ctx1.shadowBlur = 2;
                        ctx1.fillStyle = '#000';
                        ctx1.fillText("Room  " + id[i], 450 , 105 + ((i-1)/2) * (room.height + 10));
                        //ctx1.fillText(thanhvien[i] + "/4" ,400 + 351/2 , 140 + ((i-1)/2) * (67 + 20));
                        for( var j = 0 ; j < thanhvien[i] ; ++j)
                            ctx1.drawImage(player,361+ room.width/2 + j*player.width + 30,140 + ((i-1)/2) * (room.height + 10));
                    }
                    //}
                    //else
                    //break;
                }
            }

            function setPopup(w,h){
               var clientX = canvas.width;
               var clientY = canvas.height;
               var left = $(".elgg-inner")[0].style.left;
               var top = $(".elgg-inner")[0].style.top;
               $("#simplemodal-container")[0].style.left = clientX/2-w/2+left+"px";
               $("#simplemodal-container")[0].style.top = clientY/2-h/2 + top+"px";
            }


            function Option(){
        
                $('#basic-modal-content').modal();
                $("#simplemodal-container a.modalCloseImg")[0].style.display = "none";
                $("#simplemodal-container")[0].style.width= "290px";
                $("#simplemodal-container")[0].style.height="210px";
                $("#simplemodal-container")[0].style.border = "5px solid";

                $("#simplemodal-container")[0].style.backgroundColor = "#fff";
                //$("#simplemodal-container")[0].style.background='url(<?php echo elgg_get_site_url(); ?>mod/game/graphics/bg.jpg)';

                //var $ctrl = $('<textarea/>').attr({name:'text', placeholder:'OPTION', style:'left:135px;'}).addClass("textarea");
                $("#basic-modal-content").append("<strong><h3 style=\"color:black;text-align: center;\">OPTION</h3></strong><br>");

//                var $ctrl = $('<input/>').attr({type: 'radio', name: 'option', value: '0'}).addClass("option");
//                $("#basic-modal-content").append($ctrl);
//                $("#basic-modal-content").append('<a style="color:black;">Question from game Calendar</a><br>');
//
//                $ctrl = $('<input/>').attr({type: 'radio', name: 'option', value: '1', checked: 'checked', style: 'margin-top:10px;'}).addClass("option");
//                $("#basic-modal-content").append($ctrl);
//                $("#basic-modal-content").append('<a style="margin-top:10px; color:black;">Question from question bank</a><br>');

                var $ctrl = $('<a/>').attr({ name: 'option_bank', style: "background-image: url(<?php echo elgg_get_site_url(); ?>mod/game/graphics/form/bank.jpg); width: 120px; height:120px; float:left;"}).addClass("option_bank");
                $("#basic-modal-content").append($ctrl);
                
                $ctrl = $('<a/>').attr({ name: 'option_calendar', style: "background-image: url(<?php echo elgg_get_site_url(); ?>mod/game/graphics/form/calendar.jpg); background-repeat: no-repeat; width: 120px; height:120px; position: absolute; margin-left: 30px; float:left;"}).addClass("option_calendar");
                $("#basic-modal-content").append($ctrl);

                var ctrl2 = $('<input/>').attr({ type: 'button', name:'btnApply',value:'Apply', style: "float: left; position:absolute; top:170px; left:10px;"
                }).addClass("btnApply");
                $("#basic-modal-content").append(ctrl2);

                ctrl2 = $('<input/>').attr({ type: 'button', name:'btnCancel',value:'Cancel', style:'width:100px; position:absolute; top: 170px; left: 165px;'
                }).addClass("btnCancel1");
                $("#basic-modal-content").append(ctrl2);

                setPopup($("#simplemodal-container").width(), $("#simplemodal-container").height());
            }

            function Win_Form(){
                $('#basic-modal-content').modal();
                $("#simplemodal-container a.modalCloseImg")[0].style.display = "none";
                $('#basic-modal-content').empty();
                
                $("#simplemodal-container")[0].style.width= "400px";
                $("#simplemodal-container")[0].style.height="400px";
                $("#simplemodal-container")[0].style.border = "0px solid";
                $("#simplemodal-container")[0].style.backgroundRepeat = "no-repeat";
                $("#simplemodal-container")[0].style.backgroundPosition = "center";

                var farest = 0;
                for( var i in dragon){
                    if(dragon[i].x > farest)
                        farest = dragon[i].x;
						}
                if( dragon[<?php echo elgg_get_logged_in_user_guid() ?>].x == farest)                {
                    $("#simplemodal-container")[0].style.background='url(<?php echo elgg_get_site_url(); ?>mod/game/graphics/bravo.gif)';
                    <?php
                            $user = new ElggUser(elgg_get_logged_in_user_guid());
                            $user->exp += 60;
                            $user->save();
                    ?>
                }
                else{
                    $("#simplemodal-container")[0].style.background='url(<?php echo elgg_get_site_url(); ?>mod/game/graphics/good-try.gif)';
                    for( var i = 0 ; i < iCorrectAnswer ;++i){
                        <?php
                            $user = new ElggUser(elgg_get_logged_in_user_guid());
                            $user->exp += 5;
                            $user->save();
                        ?>
                    }
                }
                setPopup($("#simplemodal-container").width(), $("#simplemodal-container").height());
                ClosePopup();
            }

            function PostOnWall(){
                var t=setTimeout(function(){
                    $('#basic-modal-content').modal();
                    $("#simplemodal-container a.modalCloseImg")[0].style.display = "none";
                    $('#basic-modal-content p').remove();
                    $("#simplemodal-container").width(450);
                    $("#simplemodal-container").height("auto");
                    $("#simplemodal-container")[0].style.backgroundColor = "rgb(51,51,51)";

                    $('#basic-modal-content').append("<h3 style=\"text-align: center;\">Post On Wall</h3><br>");
                    $('#basic-modal-content').append("<p>Select questions which you want post on wall</p>");
           
                    for( var i = 0 ; i < arrQuestion.length ; i++){
                        var title = arrQuestion[i]['title'];
                        var ctrl = $('<input/>').attr({ type: 'checkbox', name:'option' + i,value: title, style:'margin-top:5px'}).addClass("chk");
                        $("#basic-modal-content").append(ctrl);
                        $("#basic-modal-content").append(title + "<br>");
                    }
                

                }, 5000);
                
                t=setTimeout(function(){
                    var $ctrl = $('<textarea/>').attr({name:'text', placeholder:'Write on your wall...'}).addClass("textarea");
                    $("#basic-modal-content").append($ctrl);
                    ctrl2 = $('<input/>').attr({ type: 'button', name:'btnPost',value:'Post'
                    }).addClass("btnPost");
                    $("#basic-modal-content").append(ctrl2);
				
                }, 5000);
			
                t=setTimeout(function(){
                    var ctrl2 = $('<input/>').attr({ type: 'button', name:'btnCancel',value:'Cancel'
                    }).addClass("btnCancel");
                    $("#basic-modal-content").append(ctrl2);
		setPopup($("#simplemodal-container").width(), $("#simplemodal-container").height());
                }, 5000);

                //setPopup($("#simplemodal-container").width(), $("#simplemodal-container").height());
            }

            function process( message){
                var data = jQuery.parseJSON(message);
                var type = data.type;
                switch(type){
                    case 'LOGIN':
                        var content = data.content;
                        if(content == '1'){
                            var $ctrl = $('<textarea/>').attr({ name:'messageBox', id: 'messageBox', style: "color:black; background-color: white; border: solid 1px black; z-index: 20; position: absolute; width: 45%; height: 102px; left: 50px; top: 460px;overflow-x:hidden; overflow-y: scroll;"}).addClass("messageBox");
                            $("#container").append($ctrl);

                            $ctrl = $('<input/>').attr({onkeypress: 'chat(event)', type: 'text', name:'chatText', id: 'chatText', placeholder:'Type here and press enter...', style: "border: solid 1px black; background-color: #fff; z-index: 20; position: absolute; left: 50px; top: 565px; width:41%; height: 25px"}).addClass("chatText");
                            $("#container").append($ctrl);

                            $ctrl = $('<input/>').attr({ type: 'button', name:'clearAllText',value:'C', id: 'clearAllText', style:"z-index: 20; position: absolute; left: 381px; top: 565px; width:30px; height: 25px"
                            }).addClass("clearAllText");
                            $("#container").append($ctrl);

                            initGame();                            
                            send("LIST_ROOM", 1);
                        }
                        else
                            alert("Your account is been playing");
                        break;
                    case 'LIST_ROOM':
                        iScene = 2;
                        canvas.style.zIndex = 1;
                        canvas1.style.zIndex = 3;
                        canvas2.style.zIndex = 2;
                        listroom = data.content;
                        ipage = listroom['slg'];
                        if( ipage == 0)
                            ipage = 1;
                        break;
                    case 'NEW_ROOM':
                        var content = data.content;
                        if(content == '1'){
                            iScene = 3;
                            canvas.style.zIndex = 2;
                            canvas2.style.zIndex = 3;
                            canvas1.style.zIndex = 1;
                        }
                        break;
                    case 'JOIN_ROOM':
                        $("#messageBox")[0].value='';
                        var content = data.content;
                        if( content == "Full")
                            alert("Full");
                        else{
                            iScene = 3;
                            canvas.style.zIndex = 1;
                            canvas2.style.zIndex = 3;
                            canvas1.style.zIndex = 1;
                            userInRoom = content;
                            dragon = new Array();
                            for( var i = 0 ; i < userInRoom['player'].length ; ++i){
                                var CharacterImage = new Image();
                                CharacterImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/xitrum.png';
                                dragon[userInRoom['player'][i]] = new Character(position['dragon' + (i+1)].x, position['dragon' + (i+1)].y, 128, 120, CharacterImage);
                                markerArray[userInRoom['player'][i]] =  [150, 250];//, 350, 450, 550, 650, 750, 850, 950];
				iSprPosArray[userInRoom['player'][i]] = 0;
                                
                                var x = new Image();
                                x.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/TabbedPane_closeButton_rolloverImage.png';
                                x_btt[userInRoom['player'][i]] = new GameButton(dragon[userInRoom['player'][i]].x, dragon[userInRoom['player'][i]].y, 21, 21,x);
                            }
                        }
                    
                        break;
                    case 'READY':
                        var content = data.content;
                        userInRoom = content;
                        break;
                    case 'UNREADY':
                        var content = data.content;
                        userInRoom = content;
                        Start = false;
                        break;
                    case 'KICK_ROOM':
                        var content = data.content;
                        userInRoom = content;
                        dragon = new Array();
                            for( var i = 0 ; i < userInRoom['player'].length ; ++i){
                                var CharacterImage = new Image();
                                CharacterImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/xitrum.png';
                                dragon[userInRoom['player'][i]] = new Character(position['dragon' + (i+1)].x, position['dragon' + (i+1)].y, 128, 120, CharacterImage);
                                markerArray[userInRoom['player'][i]] =  [150, 250, 350, 450, 550, 650, 750, 850, 950];
				iSprPosArray[userInRoom['player'][i]] = 0;

                                var x = new Image();
                                x.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/TabbedPane_closeButton_rolloverImage.png';
                                x_btt[userInRoom['player'][i]] = new GameButton(dragon[userInRoom['player'][i]].x, dragon[userInRoom['player'][i]].y, 21, 21,x);
                            }
                        break;
                    case 'BI_KICK_ROOM':
                        $("#messageBox")[0].value='';
                        iScene = 2;
                        canvas.style.zIndex = 1;
                        canvas2.style.zIndex = 2;
                        canvas1.style.zIndex = 3;
                        send("LIST_ROOM", 1);
                        $("#container").append('<div id="txtKickPlayer" style="float:left; position: absolute; top:200px; left:300px;z-index: 100; width:500px;height:200px;"><p style="margin-left:100px;margin-top:100px;color: #000; font-size: 18pt">Why does the host kick you?</p></div>');
                        $('#txtKickPlayer').delay(1000).fadeOut(500);
                        var t= setTimeout(function(){
                                $("#txtKickPlayer").remove();
                            }, 1500);
                        break;
                    case 'LIST_FREE_PLAYER':
                        var content = data.content[0];
                        var name = data.content[1];
                        var key = data.content[2];
			list_free_player = content;
                        if( content.length != 0){
                            $('#basic-modal-content').modal();
                            $("#simplemodal-container").width("auto");
                            $("#simplemodal-container").height("auto");
                            $("#simplemodal-container")[0].style.border = "2px";
                            $("#simplemodal-container")[0].style.backgroundColor = "rgb(51,51,51)";
                            $("#simplemodal-container a.modalCloseImg")[0].style.background = "url(<?php echo elgg_get_site_url();?>mod/game/graphics/x.png) no-repeat";
                            $("#simplemodal-container a.modalCloseImg")[0].style.display = "inline";
                            for( var i = 0 ; i < content.length; ++i)
                                if(content[i]['_name'] != <?php echo elgg_get_logged_in_user_guid() ?>){
                                    var ctrl = $('<input/>').attr({ type: 'button', name:i,value: "Invite " + name[i]}).addClass("btt_invite" + i);
                                    $("#basic-modal-content").append(ctrl);
                                    $("#basic-modal-content").append("<br>");

                                    var newStyle = document.createElement('style');
                                    newStyle.type = 'text/css';
                                    newStyle.innerHTML = '.btt_invite'+i+'{width: auto;'+
                                                                         'opacity: 1;'+
                                                                         'float:left;'+
                                                                         'margin:20px;'+
                                                                         'transition: opacity .25s ease-in-out;'+
                                                                         '-moz-transition: opacity .25s ease-in-out;'+
                                                                         '-webkit-transition: opacity .25s ease-in-out;}';
                                    $("head")[0].appendChild(newStyle);
                                    newStyle = document.createElement('style');
                                    newStyle.type = 'text/css';
                                    newStyle.innerHTML = '.btt_invite'+i+':hover {'+
                                                                         'opacity: 0.8;'+
                                                                         'background: #0054A7;'+
                                                                         'color: white;}'
                                   $("head")[0].appendChild(newStyle);
                                }
                        var newScript = document.createElement('script');
                        newScript.type = 'text/javascript';
                        newScript.text='for( var i = 0 ; i < list_free_player.length ; ++i){'+
                            '$(".btt_invite"+i).live("click", function(){'+
                                'send("INVITE","'+key+'");'+
                                //$.modal.close();
                            '});}';
                            $("#container").append(newScript);

                            setPopup($("#simplemodal-container").width(), $("#simplemodal-container").height());
                        }
                        else
                            alert("No one online");

			
                        break;
                    case 'INVITE':
                        var content = data.content;
                        //var r = confirm("Room " + content + " invite you for racing boat");
                        //var t= setTimeout(function(){r.hide();}, 7000);
                        //if( r == true)
                            //send("JOIN_ROOM",'"'+content+'"');
                            id_room=content;
                        invite_form.flag = 1;
                        var t= setTimeout(function(){invite_form.flag = 0;}, 7000);
                        break;
                    case 'MESSAGE':
                        var content = data.content;
                        var author = content[0];
                        if( iScene == 3){
                            var message = content[1];
                            //$("#messageBox").append('<p style="color:white; margin-left: 5px;margin-top: 5px;">'+author[0]+':  '+message+'</p>');
                            if( $("#messageBox").val())
                                $("#messageBox")[0].value = $("#messageBox").val()+"\n<strong>"+author[0]+':</strong>  '+message;
                            else
                                $("#messageBox")[0].value = author[0]+':  '+message;
                        }
                        break;
                    case 'MESSAGE_PUBLIC':
                        var content = data.content;
                        var author = content[0];
                        if( iScene == 2){
                            var message = content[1];
                            //$("#messageBox").append('<p style="color:white; margin-left: 5px;margin-top: 5px;">'+author[0]+':  '+message+'</p>');
                            if( $("#messageBox").val())
                                $("#messageBox")[0].value = $("#messageBox").val()+"\n<strong>"+author[0]+':</strong>  '+message;
                            else
                                $("#messageBox")[0].value = author[0]+':  '+message;
                        }
                        break;
                        break;
                    case 'START_GAME':
                        // show start image or draw 3, 2, 1
                        StartGame = true;
                        $("#container").append('<div id="txtStartGame" style="float:left; position: absolute; top:200px; left:300px;z-index: 100; width:500px;height:200px; background-image:url(<?php echo elgg_get_site_url(); ?>mod/game/graphics/fireworks-12.gif);"><strong><p style="margin-left:100px;margin-top:100px;color: #ff0000; font-size: 40pt">START GAME</p></strong></div>');
                        $('#txtStartGame').delay(1500).fadeOut(1000);                        
                        var t= setTimeout(function(){
                                $("#txtStartGame").remove();
                            }, 2500);

                        if(userInRoom['host'] == <?php echo elgg_get_logged_in_user_guid() ?>){
                            var t= setTimeout(function(){                                
                                send("DRAW_QUES",option);
                            }, 2700);
                        }
                        
                        for( var i = 0 ; i < userInRoom['ready'].length ; ++i)
                            userInRoom['ready'][i] = 0;
                        isReady = false;
                        break
                    case 'HAVE_RIGHT_ANSWER':
                        if(data.content != -1){
                            right = data.content;
                        }
                        else{
                            right = null;
                            if(userInRoom['host'] == <?php echo elgg_get_logged_in_user_guid() ?>){
                                var t= setTimeout(function(){
                                    send("DRAW_QUES",option);
                                }, 2000);
                            }
                            var t= setTimeout(function(){
                            right = null;
                            actualprogress = 0;
                            for( var i = 0; i < radio.length; i++){
                                if (radio[i].check == true){
                                    radio[i].check = false;
                                    break;
                                }
                            }
                        }, 2000);
                            var t= setTimeout(function(){
                                actualprogress = 0;
                            }, 2000);
                        }
                        autoMove =  true;
                
                        break;
                    case 'QUIT_ROOM':
                        var content = data.content;
                        userInRoom = content;
                        dragon = new Array();
                            for( var i = 0 ; i < userInRoom['player'].length ; ++i){
                                var CharacterImage = new Image();
                                CharacterImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/xitrum.png';
                                dragon[userInRoom['player'][i]] = new Character(position['dragon' + (i+1)].x, position['dragon' + (i+1)].y, 128, 120, CharacterImage);
                                markerArray[userInRoom['player'][i]] =  [150, 250, 350, 450, 550, 650, 750, 850, 950];
				iSprPosArray[userInRoom['player'][i]] = 0;

                                var x = new Image();
                                x.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/TabbedPane_closeButton_rolloverImage.png';
                                x_btt[userInRoom['player'][i]] = new GameButton(dragon[userInRoom['player'][i]].x, dragon[userInRoom['player'][i]].y, 21, 21,x);
                            }
                        break
                    case 'QUIT_GAME':
                        var content = data.content;
                        userInRoom = content;
                        break;
                    case 'FINISH_GAME':
                        question = null;
                        var content = data.content; // GUID of winner
                        for( var i = 0; i < radio.length; i++){
                            if (radio[i].check == true){
                                radio[i].check = false;
                                break;
                            }
                        }

                        right = null;
                        StartGame = false;
                        var progress = document.getElementById("progressbar");
                        progress.style.border = "0px solid black";
			var indicator = document.getElementById("indicator");
                        actualprogress = 0;
                        indicator.style.width=actualprogress + "px";
                        Win_Form();
                        PostOnWall(); // show popup post question to the wall
                        break;
                    case 'DRAW_QUES':
                        question = data.content;
                        var indicator = document.getElementById("indicator");
                        indicator.style.background ='url(<?php echo elgg_get_site_url(); ?>mod/game/graphics/green.png)';
                        arrQuestion.push(question); // add to array question which is showed in scene2

                        switch(parseInt(question['type'])){
                            case 1:
                                for(var i =0; i<4;i++) {
                                    var radio_uncheckImage  = new Image();
                                    var radio_checkImage  = new Image();
                                    radio_uncheckImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/radio_uncheck.png';
                                    radio_checkImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/radio_checked.png';
                                    if( i%2 == 0)
                                        radio[i] = new Radio(canvas2.width/3 - 150, 55 + i*13, 19,19, radio_checkImage, radio_uncheckImage );
                                    else
                                        radio[i] = new Radio(canvas2.width/3 + 150, 55 + (i-1)*13, 19,19, radio_checkImage, radio_uncheckImage );
                                }
                                break;
                            case 2:
                                for(var i =0; i<3;i++) {
                                    var radio_uncheckImage  = new Image();
                                    var radio_checkImage  = new Image();
                                    radio_uncheckImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/radio_uncheck.png';
                                    radio_checkImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/radio_checked.png';                                    
                                    radio[i] = new Radio(150 + i*100, 45 , 19,19, radio_checkImage, radio_uncheckImage );
                                }
                                break;
                            default:
                                break;
                        }
                        break;
                    case 'OUT_OF_QUESTION':
                        send("FINISH_GAME","");
                        break;
                    case 'TYPE_QUESTION':
                        option = data.content;
                        //set global variable type_question =
                        break;
                    default: break;
                    }
                }

            function send(type, content){
                    ws.send(JSON.stringify({type:type, author: <?php echo elgg_get_logged_in_user_guid() ?>, content:content}));

                }

            function connect(){
                    var ws_uri = "ws://192.168.1.111:85/elgg-1.8.3/mod/game/server/server.php";
                    try{
                var appType;

                if (typeof MozWebSocket !== "undefined") {
                    appType = "Mozilla";
                } else if (window.WebSocket) {
                    appType = "Chrome";
                }

                if (appType == "Mozilla") {
                    ws = new MozWebSocket(ws_uri);
                } else {
                    ws = new WebSocket(ws_uri);
                }
                        //ws = new WebSocket(ws_uri);

                        ws.onopen = function(){
                            send("LOGIN", "");
                        };

                        ws.onmessage = function(evt){
                            process(evt.data);
                
                        };

                        ws.onclose = function(){
                            //$("#container").empty();
                            autoMove = false;
                            clearInterval(itv);
                            alert('Cannot connect to server. Try again!');
                        };

                        ws.onerror =function (evt) {
                            alert('Cannot connect to server. Try again!' + evt);
                        };
                    }
                    catch(exception){
                        alert('Cannot connect to server. Try again!');
                    }
                }

            function ClosePopup()
                {
                    var t=setTimeout("$.modal.close();",4000);
                }
</script>

<script>
        function chat(e){
            if(e.which == 13){
                if( iScene == 3)
                    send("MESSAGE", $('#chatText').val());
                else if( iScene ==2)
                    send("MESSAGE_PUBLIC", $('#chatText').val());
                $('#chatText')[0].value = '';
            }
        }
</script>
<div id="container">
    <div id="progressbar"  style="float:left; position: absolute; z-index: 4; top: 46px;left: 470px;display: block;">
        <div id="indicator"></div>
    </div>

    <a id="LoadImage" style="z-index:7;background-image: url(<?php echo elgg_get_site_url(); ?>mod/game/graphics/Loading.gif); top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; position: absolute"></a>

    <canvas id="scene1" style="z-index: 2;position:absolute;top:20px;left:0px;" width="1100px" height="600px"></canvas>
    <canvas id="scene2" style="z-index: 1;position:absolute;top:40px;left:300px;" width="700px" height="140px"></canvas>
    <canvas id="scene" style="z-index: 3;position:relative;top:0px;left:0px;" width="1100px" height="600px"></canvas>
    <script type="text/javascript" language="javascript">
            connect();
    </script>
 <div id="content">
        <div id="basic-modal-content">            
        </div>
    </div>

    <script>
            $(".btnCancel").live("click", function(){
                arrQuestion = new Array();
                        iCorrectAnswer = 0;
                $.modal.close();  
                if(play_with_pc){
                    send("QUIT_ROOM","");
                    play_with_pc = false;
                }
                else{
                    send("JOIN_ROOM", '"'+id_room+'"');
                }
            });

            $(".btnCancel1").live("click", function(){
                $.modal.close();  
            });

            $(".option_bank").live("click", function(){
                options = 1;
            });

            $(".calendar_bamk").live("click", function(){
                options = 0;
            });
    </script>

    <script>
            $(".btnApply").live("click", function(){
                option = $("#basic-modal-content input[type='radio']:checked").val();
                send("TYPE_QUESTION", option);
                $.modal.close();
            });

            $(".btnPost").live("click", function(){
                var len = arrQuestion.length;
                for( var i = 0 ; i< len ; ++i){
                    if(!$('input[name=option' + i + ']').is(':checked'))
                    {
                        arrQuestion.splice(i, 1);
                    }
                }
                if( arrQuestion != null){
                    var xmlHttp;
                    if (window.XMLHttpRequest) {
                        xmlHttp = new XMLHttpRequest();
                    }
                    else {
                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    xmlHttp.onreadystatechange = function () {
                        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                            //alert(xmlHttp.responseText);
                            $.modal.close();
                            if(play_with_pc){
                                send("QUIT_ROOM","");
                                play_with_pc = false;
                            }
                            else{
                                for( var i = 0 ; i < userInRoom['player'].length ; ++i){
                                var CharacterImage = new Image();
                                CharacterImage.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/dragon.gif';
                                dragon[userInRoom['player'][i]] = new Character(position['dragon' + (i+1)].x, position['dragon' + (i+1)].y, dragonW, dragonH, CharacterImage);
                                markerArray[userInRoom['player'][i]] =  [150, 250];//, 350, 450, 550, 650, 750, 850, 950];

                                var x = new Image();
                                x.src = '<?php echo elgg_get_site_url(); ?>mod/game/graphics/TabbedPane_closeButton_rolloverImage.png';
                                x_btt[userInRoom['player'][i]] = new GameButton(dragon[userInRoom['player'][i]].x, dragon[userInRoom['player'][i]].y, 21, 21,x);
                            }
                                //send("JOIN_ROOM", id_room);
                            }
                        }
                    }

                    xmlHttp.open("GET", "save_thewire?type="+option+"&t=" + new Date().getTime() + "&arrQuestion=" + JSON.stringify(arrQuestion) + "&input=" + $("#basic-modal-content .textarea").val(), true);
                    xmlHttp.send(null);
                }
                arrQuestion = new Array();
                iCorrectAnswer = 0;
            });
    </script>
</div>
<script>
        $("#clearAllText").live("click", function(){
            $("#messageBox")[0].value='';            
        });
</script>